package com.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lkd.constant.MessageConstant;
import com.lkd.dto.PartnerDto;
import com.lkd.entity.Partner;
import com.lkd.exception.BusinessException;
import com.lkd.mapper.PartnerMapper;
import com.lkd.result.PageBean;
import com.lkd.service.PartnerService;
import com.lkd.vo.PartnerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class PartnerServiceImpl implements PartnerService {
    @Autowired
    private PartnerMapper partnerMapper;

    @Override
    public void savePartner(PartnerDto partnerDto) {
        String mobile = partnerDto.getMobile();
        Partner opartner = partnerMapper.selectByMobile(mobile);
        if (opartner != null) {
            throw new BusinessException(MessageConstant.PHONE_EXISTS);
        }
        Partner partner = BeanUtil.toBean(partnerDto, Partner.class);
//        partner.setPassword(SecureUtil.md5(partner.getPassword()));
        partner.setStatus(1);
        partner.setCreateTime(LocalDateTime.now());
        partner.setUpdateTime(LocalDateTime.now());
        partnerMapper.savePartner(partner);
    }

    @Override
    public PageBean<PartnerVo> pageConditionQuery(Integer pageIndex, Integer pageSize, String name) {
        PageHelper.startPage(pageIndex, pageSize);
        Page<PartnerVo> page = (Page<PartnerVo>) partnerMapper.selectByConditon(name);
        page.forEach(partnerVo -> {
            partnerVo.setPassword("");
        });
        Long totalPage = (long) page.getPages();
        return new PageBean<PartnerVo>(pageIndex, pageSize, totalPage, page.getTotal(), page.getResult());
    }

    @Override
    public PartnerVo selectById(Integer id) {
        PartnerVo partnerVO = partnerMapper.selectById(id);
        partnerVO.setPassword(null);
        partnerVO.setEmail(null);
        partnerVO.setProvince(null);
        partnerVO.setCity(null);
        partnerVO.setCounty(null);
        partnerVO.setAddr(null);
        partnerVO.setStatus(null);
        partnerVO.setCreateTime(null);
        partnerVO.setUpdateTime(null);
        return partnerVO;
    }

    @Override
    public void updateById(PartnerDto partnerDto) {
        Partner partner = BeanUtil.toBean(partnerDto, Partner.class);
        partner.setUpdateTime(LocalDateTime.now());
        partnerMapper.updateById(partner);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Integer id) {
        partnerMapper.deleteById(id);
//        vendingMachineService.deleteByPartnerId(id); 解开此行删除合作商对应的设备表
    }

    @Override
    public int count() {
        int count = partnerMapper.count();
        return count;
    }
}